package com.town.garden.strategy.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.town.garden.component.RedisRepository;
import com.town.garden.constant.GlobalConstant;
import com.town.garden.entiy.AlarmList;
import com.town.garden.entiy.AlertEvent;
import com.town.garden.entiy.ChannelAlarm;
import com.town.garden.enums.AlertEventEnum;
import com.town.garden.storage.NvrSessionStorage;
import com.town.garden.strategy.ProcessAlarmEventStrategy;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @Description 通道告警解析策略
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/5/16
 */
@Component
@AllArgsConstructor
@Slf4j
public class ProcessChannelAlarmStrategyImpl implements ProcessAlarmEventStrategy {
    private final RedisRepository redisRepository;

    @Override
    public boolean isMatch(List<AlarmList> alarmList) {
        if (CollectionUtil.isNotEmpty(alarmList)) {
            for (AlarmList alarmList1 : alarmList
            ) {
                if (CollectionUtil.isNotEmpty(alarmList1.getChannelAlarm())) {
                    return true;
                }
            }
        } else {
            return false;
        }
        return false;
    }

    @Override
    public void doProcessAlarmEvent(List<AlarmList> alarmList) {
        for (AlarmList alarmList1 : alarmList
        ) {
            if (Objects.nonNull(alarmList1)&&CollectionUtil.isNotEmpty(alarmList1.getChannelAlarm())) {
                for (ChannelAlarm channelAlarm : alarmList1.getChannelAlarm()
                ) {
                    if (Objects.nonNull(channelAlarm.getIntAlarm()) && channelAlarm.getIntAlarm().getAlarmVal()) {
                        //转换告警时
                        DateTime dateTime = DateUtil.parse(alarmList1.getTime(), GlobalConstant.NVR_ALARM_TIME_FORMAT);
                        String time = DateUtil.format(dateTime, DatePattern.NORM_DATETIME_PATTERN);
                        //封装统一事件对象 放入redis队列中
                        AlertEvent alertEvent = new AlertEvent(channelAlarm.getChannel(),
                                time, AlertEventEnum.getEnumByName(channelAlarm.getIntAlarm().getIntSubtype()),
                                NvrSessionStorage.CHANNEL_IP_MAP.get(channelAlarm.getChannel())
                        );
                        log.info("execute do process channelAlarmEvent");
                        redisRepository.leftPush(GlobalConstant.ALARM_EVENT_KEY, alertEvent);
                    }
                }

            }
        }
    }
}
